<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>递归</title>
</head>

<body>

    <script>
        //使用递归函数计算n的阶层
        function jc(n) {
            if (n == 1) {
                return 1;
            } else {
                return n * jc(n - 1);
            }
        }
        console.log(jc(5));

        //斐波那契数列  1 1 2 3 5 8 13 21 34 55
        function fn(n) {
            if (n == 1 || n == 2) {
                return 1;
            };
            return fn(n - 2) + fn(n - 1);
        }
        console.log(fn(10));


        var data = [
            {
                id: 1,
                name: '家用电器',
                goods: [
                    {
                        id: 11,
                        name: '空调',
                        goods: [
                            {
                                id: 111,
                                name: '挂式空调',
                                goods: [
                                    {
                                        id: 1111,
                                        name: '美的',
                                        goods: []
                                    },
                                    {
                                        id: 1112,
                                        name: '格力',
                                        goods: []
                                    }
                                ]
                            },
                            {
                                id: 112,
                                name: '柜式',
                                goods: []
                            }
                        ]
                    }
                ]
            }
        ]

        function getId(json, id) {
            let obj = {};
            //利用forEach去遍历每一个对象
            json.forEach((item) => {
                if (item.id == id) {
                    obj = item;
                    // console.log(item)
                }
                //我们想要得到里层的数据11 12 可以利用递归函数
                //里面有goods这个数组且长度大于0
                else if (item.goods && item.goods.length > 0) {
                    obj = getId(item.goods, id);
                }
            });

            return obj;
        }
        console.log(getId(data, 1112));
    </script>
</body>

</html>